package com.rajesh.messageservice;

import android.content.Context;

import com.google.gson.GsonBuilder;
import com.rajesh.messageservice.bean.Action;
import com.rajesh.messageservice.crack.ContactService;
import com.rajesh.messageservice.crack.HeadImgService;
import com.rajesh.messageservice.helper.DownloadHelper;
import com.rajesh.messageservice.helper.GlobalConfig;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.io.File;
import java.net.URI;

public class SocketClient extends WebSocketClient {
    private Context context = null;

    public SocketClient(Context context, URI uri){
        super(uri);
        this.context = context;
    }

    @Override
    public void onOpen(ServerHandshake serverHandshake) {
    }

    @Override
    public void onMessage(String s) {
        Action action = new GsonBuilder().create().fromJson(s, Action.class);
        try{
            switch (action.getType()){
                case SignIn:{
                    String linkQrCode = action.getArgs().get("QrCode").toString();
                    File qrCodeDirectory = new File(GlobalConfig.QrCodePath);
                    for (File qrCode: qrCodeDirectory.listFiles()) {
                        qrCode.delete();
                    }
                    DownloadHelper.getFile(linkQrCode, System.currentTimeMillis()+".jpg", GlobalConfig.QrCodePath);
                    break;
                }
                case SyncContacts:{
                    ContactService.syncContacts(this.context);
                    HeadImgService.syncHeadImages(this.context);
                    break;
                }
                default:{
                    break;
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void onClose(int i, String s, boolean b) {

    }

    @Override
    public void onError(Exception e) {

    }
}
